package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.ImageManager;
import com.eims.sls_app.view.MyToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import bls.juejin.cn.R;

public class AutomaticRechargeActivity extends MyBaseActivity implements OnClickListener {
    private ImageButton ibBack;
    private TextView tvSumbit;
    private ImageView ivErwei;
    private Bitmap bitmap;
    public String TAG = "AutomaticRechargeActivity";
    private String url;

    private String opt, auth, info, time, imei, crc; // 格式化后的参数

    private MyHandler mHandler;
    private MyAsynTask mMyAsynTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.automatic_recharge);

        mHandler = new MyHandler();
        mMyAsynTask = new MyAsynTask();
        mMyAsynTask.execute();
        init();
    }

    private void init() {

        ibBack = (ImageButton) findViewById(R.id.btn_back);


        tvSumbit = (TextView) findViewById(R.id.tv_saoma_pay);
        ivErwei = (ImageView) findViewById(R.id.iv_erwei_bg);

        ibBack.setOnClickListener(this);
        tvSumbit.setOnClickListener(this);


//        createQRImage(url);

    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.tv_saoma_pay:


                new Task().execute(App.url+url);
//                bitmap=GetImageInputStream(App.url+url);
//
//                Log.e(TAG, "onClick: "+App.url+url);
//                saveImageToGallery(AutomaticRechargeActivity.this, bitmap);

                break;
            default:
                break;
        }
    }

    /**
     * 异步线程下载图片
     *
     */
    class Task extends AsyncTask<String, Integer, Void>{

        protected Void doInBackground(String... params) {
            bitmap=GetImageInputStream((String)params[0]);
            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mHandler.sendEmptyMessage(15);

        }

    }






    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // String fileName = System.currentTimeMillis() + ".jpg";
        String fileName = "pay_mitiyu.jpg";
        File file = new File(appDir, fileName);


        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getPath())));

        MyToast.getToast(AutomaticRechargeActivity.this, "二维码已保存！").show();


    }

    class MyAsynTask extends AsyncTask<Integer, Integer, String> {

        String error = "-1";

        @Override
        protected String doInBackground(Integer... params) {
            info = "";
            opt = "115";
            time = RspBodyBaseBean.getTime();
            imei = RspBodyBaseBean.getIMEI(AutomaticRechargeActivity.this);
            // info = RspBodyBaseBean.change_TheSun(schemeId+"", context_Sun);

            // String key = MD5.md5(App.user.getUserPass() +
            // App.MD5_key);
            String key = App.key;

            crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
            auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());


            String[] values = {opt, auth, info};
            Log.e(TAG, "晒单" + RequestParams.convertParams(AutomaticRechargeActivity.this, opt, info));
            String result = HttpUtils.doPost(App.names, values, App.path);
            System.out.println("晒单：" + result);


            try {

                JSONArray 	arr = new JSONArray(result);
                JSONObject temp = (JSONObject) arr.get(0);
                url = temp.getString("Value");


                Log.e(TAG, "晒单" + url);

                error = "1";
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                error = "-1";
                Log.e("x", "MyCenterActivity异常" + e.getMessage());
            }


            return error;
        }

        @Override
        protected void onPostExecute(String result) {

            mHandler.sendEmptyMessage(Integer.parseInt(result));

            super.onPostExecute(result);
        }
    }

    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:

                    break;
                case 15:
                    saveImageToGallery(AutomaticRechargeActivity.this, bitmap);
                    break;
                case 1:


                    ImageManager.getInstance().displayImage(App.url+url, ivErwei, ImageManager.getViewsNOHuancunHeadOptions());




                    break;


                case -1:

                    break;
                case -500:

                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }

    }
    /**
     * 获取网络图片
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public Bitmap GetImageInputStream(String imageurl){
        URL url;
        HttpURLConnection connection=null;
        Bitmap bitmap=null;
        try {
            url = new URL(imageurl);
            connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream=connection.getInputStream();
            bitmap= BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }



}
